package cs236369.hw5;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServlet;

import utils.DBConnector;

public class SearchWS {
	
	public java.lang.String[] search(java.lang.String[] keywords) {
		String query = "SELECT course_name, description FROM courses WHERE is_active = TRUE ";
		
		for (int i = 0; i < keywords.length; i++) {
			if (keywords[i] != null )query += "AND description LIKE CONCAT('%', ?, '%') ";
		}
		
		DBConnector dbConn = null;
		try {
			dbConn = new DBConnector();
		
		
		
			PreparedStatement stmnt = dbConn.getConnection().prepareStatement(query);
		
			for (int i = 0; i < keywords.length; i++) {
				if (keywords[i] != null ) stmnt.setString(i + 1, keywords[i]);
			}

			ResultSet res = stmnt.executeQuery();
			
						
			res.last();
			if (res.getRow() == 0) {
				return null;
			}
			
			String[] result = new String[res.getRow()];
			
			res.beforeFirst();
			
			int i = 0;
			while (res.next()) {
				String courseDetails = res.getString(1) + "||" + res.getString(2);
				result[i++] = courseDetails;
			}
			
			return result;
		}		
		
		
		catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return null;

		
	}

}
